<template>
  <div class="container mx-auto px-4 py-8 max-w-4xl">
    <header class="mb-8 text-center">
      <h1 class="text-3xl font-bold text-blue-600 mb-2">智能纸箱计算系统</h1>
      <p class="text-gray-600">专业立式摆放优化方案</p>
    </header>

    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <h2 class="text-xl font-semibold mb-4">书籍参数</h2>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">书籍尺寸 (毫米)</label>
              <div class="flex gap-2">
                <input type="number" v-model="width" placeholder="宽度"
                  class="input-transition w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="1" required>
                <input type="number" v-model="height" placeholder="立式高度"
                  class="input-transition w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="1" required>
                <input type="number" v-model="length" placeholder="厚度"
                  class="input-transition w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  min="1" required>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">单本重量 (公斤)</label>
              <input type="number" v-model="bookWeight" step="0.001"
                class="input-transition w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                min="0.001" required>
            </div>
          </div>
        </div>
      </div>

      <button @click="calculate"
        class="w-full mt-4 bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors duration-200">
        立即计算
      </button>
    </div>

    <div v-if="results.length > 0" class="space-y-6">
      <div v-for="(result, index) in results" :key="index" class="result-section">
        <h3>{{ result.title }}</h3>
        <template v-if="result.type === 'standard' && result.box">
          <p>匹配箱型：<strong>{{ result.box.name }}</strong>（外径：{{ result.box.size.join("×") }}mm）</p>
          <p>实际内径：{{ result.innerSize.join("×") }}mm</p>
          <p>最大装载量：{{ result.actualCount }}本</p>
          <p>├─ 体积限制：{{ result.volumeCount }}本</p>
          <p>└─ 重量限制：{{ result.weightCount }}本</p>
          <p>空间利用率：{{ result.utilization.toFixed(1) }}%</p>
        </template>
        <template v-else-if="result.type === 'standard'">
          <p>⚠️ 无合适标准箱型</p>
        </template>
        <template v-else-if="result.type === 'custom'">
          <p>推荐外径尺寸：<strong>{{ result.customInner.join("×") }}mm</strong></p>
          <p>最大装载量：{{ result.actualCustom }}本</p>
          <p>├─ 体积限制：{{ result.customVolume }}本</p>
          <p>└─ 重量限制：{{ result.customWeight }}本</p>
          <p>空间利用率：{{ result.customUtilization.toFixed(1) }}%</p>
          <p :class="getSafetyClass(result.safetyMargin)">安全系数：{{ result.safetyMargin.toFixed(1) }}倍</p>
        </template>
      </div>
    </div>

    <div class="mt-6 p-4 bg-blue-50 rounded-lg text-sm text-blue-800">
      <p class="mb-2">📦 计算说明：</p>
      <ul class="list-disc pl-5 space-y-1">
        <li>高度方向自动预留5mm缓冲空间</li>
        <li>长宽方向采用智能排列算法优化</li>
        <li>重量限制基于15kg标准承重计算</li>
        <li>3D可视化展示最佳摆放方式</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const width = ref('');
const height = ref('');
const length = ref('');
const bookWeight = ref('');
const results = ref<any[]>([]);

const POSTAL_BOXES = {
  '1号': [530, 290, 370],
  '2号': [530, 230, 290],
  '3号': [430, 210, 270],
  '4号': [350, 190, 230],
  '5号': [290, 170, 190],
  '6号': [260, 150, 180],
  '7号': [230, 130, 160],
  '8号': [210, 110, 140],
  '9号': [195, 105, 135],
  '10号': [175, 95, 115],
  '11号': [145, 85, 105],
  '12号': [130, 80, 90]
};

function calculateStandardBox(dims: number[]) {
  const [l, w, h] = dims;
  const boxes = Object.entries(POSTAL_BOXES).sort((a, b) =>
    a[1][0] * a[1][1] * a[1][2] - b[1][0] * b[1][1] * b[1][2]);

  for (const [name, size] of boxes) {
    const [L, W, H] = size;
    if (h > H - 15) continue;
    const condition1 = (l <= L - 15) && (w <= W - 15);
    const condition2 = (w <= L - 15) && (l <= W - 15);
    if (condition1 || condition2) return { name, size };
  }
  return null;
}

function calculateCustomBox(dims: number[], weight: number) {
  const [l, w, h] = dims;
  const maxLW = Math.max(l, w);
  const minLW = Math.min(l, w);
  const weightLimit = 15;
  const maxByWeight = Math.floor(weightLimit / weight);
  const requiredDepth = maxByWeight * l + 10;

  return [
    maxLW + 15,
    minLW * maxByWeight + 15,
    h + 15
  ];
}

function calculateCapacity(boxInnerSize: number[], productDims: number[]) {
  const [L, W, H] = boxInnerSize;
  const [l, w, h] = productDims;

  if (H < h) return 0;
  const layers = Math.floor(H / h);

  const way1 = Math.floor(L / l) * Math.floor(W / w);
  const way2 = Math.floor(L / w) * Math.floor(W / l);
  return Math.max(way1, way2) * layers;
}

function getSafetyClass(safetyMargin: number) {
  if (safetyMargin < 1.5) return 'text-red-600';
  if (safetyMargin < 2) return 'text-orange-500';
  return 'text-green-600';
}

function calculate() {
  const dims = [
    Number(length.value),
    Number(width.value),
    Number(height.value)
  ];
  const weight = Number(bookWeight.value);
  const bookVolume = dims[0] * dims[1] * dims[2];
  results.value = [];

  // 标准箱计算
  const standardBox = calculateStandardBox(dims);
  const standardResult: any = {
    type: 'standard',
    title: '标准箱计算结果'
  };

  if (standardBox) {
    const innerSize = standardBox.size.map(d => d - 15);
    const volumeCount = calculateCapacity(innerSize, dims);
    const weightCount = Math.floor(15 / weight);
    const actualCount = Math.min(volumeCount, weightCount);
    const innerVolume = innerSize[0] * innerSize[1] * innerSize[2];
    const utilization = (actualCount * bookVolume) / innerVolume * 100;

    Object.assign(standardResult, {
      box: standardBox,
      innerSize,
      volumeCount,
      weightCount,
      actualCount,
      utilization
    });
  }
  results.value.push(standardResult);

  // 定制箱计算
  const customInner = calculateCustomBox(dims, weight);
  const customVolume = calculateCapacity(customInner, dims);
  const boxBaseArea = (customInner[0] * customInner[1]) / 100;
  const maxLoadKg = boxBaseArea * 0.15;
  const customWeight = Math.floor(15 / weight);
  const actualCustom = Math.min(customVolume, customWeight);
  const customInnerVolume = customInner[0] * customInner[1] * customInner[2];
  const customUtilization = (actualCustom * bookVolume) / customInnerVolume * 100;
  const safetyMargin = maxLoadKg / (actualCustom * weight);

  results.value.push({
    type: 'custom',
    title: '定制箱计算结果',
    customInner,
    customVolume,
    customWeight,
    actualCustom,
    customUtilization,
    safetyMargin
  });
}
</script>

<style scoped>
.result-section {
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.result-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.input-transition {
  transition: all 0.3s ease;
}

.input-transition:focus {
  transform: scale(1.05);
  box-shadow: 0 0 8px rgba(59, 130, 246, 0.5);
}

@keyframes pulse {
  50% {
    opacity: 0.5;
  }
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
</style> 